'''
Description: 
Author: Zilu
Date: 2021-11-07 16:48:54
Version: 
LastEditTime: 2021-11-07 17:13:18
LastEditors: Zilu
'''

# 使用@property可以将方法调用转换成类的属性
class Student(object):
    def __init__(self) -> None:
        super().__init__()
        self.score = 0

    @property
    def getScore(self):
        return self.score

    @getScore.setter
    def setScore(self, value):
        if (not isinstance(value,(int,float))):
            raise ValueError("score must be a number")
        elif value < 0 or value > 100:
            print('score must between 0~100')
        else:
            self.score = value

s = Student()
s.getScore      # 实际上是调用s.getScore()
s.setScore = 60
s.setScore = 9999       #使用错误
s.setScore = '68'       #使用错误

# @property 也是一个装饰器，负责把一个方法变成属性调用
# 使用@property修饰一个getter方法时，除了它变成属性，还创建了另外一个setter装饰器
# 如果使用了@property 后，不适用setter装饰器，可以定义只读属性

# 不过需要注意，如果使用@property修饰成属性后，不能再定义同名属性，否则可能回无限递归，造成栈溢出错误

# 练习：请利用@property给一个Screen对象加上width和height属性，以及一个只读属性resolution
class Screen(object):
    @property
    def width(self):
        return self.__width

    @width.setter
    def width(self, value):
        if (not isinstance(value,int)):
            raise ValueError("width must be a integer")
        elif value < 0 or value > 10000:
            print('width must between 0~10000')
        else:
            self.__width = value

    @property
    def height(self):
        return self.__height

    @height.setter
    def height(self, value):
        if (not isinstance(value,(int))):
            raise ValueError("height must be a integer")
        elif value < 0 or value > 10000:
            print('height must between 0~10000')
        else:
            self.__height = value

    @property
    def resolution(self):
        return self.__width * self.__height

screen = Screen()
screen.width = 1024

    


